/**
 * 
 */
package ${basepackage}.manager.impl.op;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import com.excalibur.shiro.shiro.util.ShiroUtils;
import com.excalibur.core.util.date.DateUtils;
import com.excalibur.core.util.SpringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ${basepackage}.constant.SystemConstant;
import ${basepackage}.manager.op.RoleManager;
import ${basepackage}.manager.exception.ServiceException;
import ${basepackage}.mapper.op.AuthorityMapper;
import ${basepackage}.mapper.op.RoleMapper;
import ${basepackage}.model.criteria.op.RoleCriteria;
import ${basepackage}.model.po.op.Authority;
import ${basepackage}.model.po.op.Role;
import ${basepackage}.model.po.op.RoleAuthority;
import ${basepackage}.model.vo.common.Page;
import ${basepackage}.model.vo.op.role.AddRoleForm;
import ${basepackage}.model.vo.op.role.RoleRow;
import ${basepackage}.model.vo.op.role.UpdateRoleForm;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;

/**
 * @author "Jiance Qin"
 * 
 * @date 2014年2月24日
 * 
 * @time 下午5:32:54
 * 
 */
@Service
public class RoleManagerImpl implements RoleManager {

	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private AuthorityMapper authorityMapper;

	/**
	 * 
	 */
	public RoleManagerImpl() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.general.op.manager.RoleManager#delete(java.lang.Long)
	 */
	@Override
	public boolean delete(Long id) throws ServiceException {
		if (id == null) {
			throw new ServiceException(
					SpringUtils
							.getI18nMessage("webapp.service.RoleManagerImpl.delete.IdNotNull"));
		}
		// 检查角色是否存在
		if (roleMapper.get(id) == null) {
			throw new ServiceException(
					SpringUtils
							.getI18nMessage("webapp.service.RoleManagerImpl.delete.NotExist"));
		}
		roleMapper.remove(id);
		// 删除权限信息
		authorityMapper.deleteRoleAuthorityByRoleId(id);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.general.op.manager.RoleManager#getRoles(com.general.op.model.
	 * criteria.RoleCriteria, int, int)
	 */
	@Override
	public Page<RoleRow> getRoles(RoleCriteria criteria, int offset,
			int limit) throws ServiceException {
		if (criteria == null) {
			throw new ServiceException(
					SpringUtils
							.getI18nMessage("webapp.service.RoleManagerImpl.getRoles.CriteriaNotNull"));
		}
		if (offset < 0) {
			offset = 0;
		}
		if (limit < 1) {
			limit = 1;
		}

		Page<RoleRow> roleRowList = new Page<RoleRow>();
		PageList<Role> roleList = roleMapper.getList(criteria, new PageBounds(offset,
				limit, true));
		roleRowList.setTotal(Long.valueOf(roleList.getPaginator().getTotalCount()));

		List<Role> resultRoleList = new ArrayList<Role>(roleList);
		if (roleList != null) {
			List<Authority> authoList = null;
			for (Role role : roleList) {
				authoList = authorityMapper.getByRoleId(role.getId());
				if (authoList != null) {
					role.setAuths(new LinkedHashSet<Authority>(authoList));
					// 检查当前用户是否为超级管理员，如果不是，则去掉具有超级管理员中心各种权限的角色
					for (Authority autho : authoList) {
						if (autho.getName().startsWith(
								SystemConstant.SUPER_ADMIN_AUTHO)) {
							if (!ShiroUtils
									.isPermitted(SystemConstant.SUPER_ADMIN_AUTHO)) {
								resultRoleList.remove(role);
							}
						}
					}
				}
			}
		}
		List<RoleRow> rowList = createRoleRowList(resultRoleList);
		roleRowList.setRows(rowList);

		return roleRowList;
	}

	/**
	 * 创建前台显示角色信息对象列表.
	 * 
	 * @param list
	 * @return
	 */
	protected List<RoleRow> createRoleRowList(List<Role> list) {
		if (list == null || list.isEmpty()) {
			return null;
		}
		List<RoleRow> rowList = new ArrayList<RoleRow>();
		RoleRow row;
		for (Role role : list) {
			row = createRoleRow(role);
			if (row != null) {
				rowList.add(row);
			}
		}
		return rowList;
	}

	/**
	 * 创建前台显示角色信息对象.
	 * 
	 * @param role
	 * @return
	 */
	protected RoleRow createRoleRow(Role role) {
		if (role == null) {
			return null;
		}
		RoleRow row = new RoleRow();
		row.setId(role.getId());
		row.setName(role.getName());
		row.setDisplayName(role.getDisplayName());
		row.setCreateTime(DateUtils.formatAsString(role.getCreateTime()));
		row.setUpdateTime(DateUtils.formatAsString(role.getUpdateTime()));
		Set<Authority> authoList = role.getAuths();
		if (authoList != null) {
			StringBuilder authoes = new StringBuilder();
			List<Long> authoIds = new ArrayList<Long>();
			for (Authority autho : authoList) {
				if (authoes.length() != 0) {
					authoes.append("，");
				}
				authoes.append(autho.getDisplayName()).append("(")
						.append(autho.getName()).append(")");
				authoIds.add(autho.getId());
			}
			row.setAuthoIds(authoIds);
			row.setAuthoes(authoes.toString());
		}
		return row;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.general.op.manager.RoleManager#addRole(com.general.op.model.vo
	 * .AddRoleForm)
	 */
	@Override
	public RoleRow addRole(AddRoleForm addRoleForm) throws ServiceException {
		if (addRoleForm == null) {
			throw new ServiceException(
					SpringUtils
							.getI18nMessage("webapp.service.RoleManagerImpl.addRole.FormNotNull"));
		}
		// 检查角色名是否存在
		if (isRoleNameExist(addRoleForm.getName(), null)) {
			throw new ServiceException(
					SpringUtils
							.getI18nMessage("webapp.service.RoleManagerImpl.addRole.IsExist"));
		}
		// 检查权限是否存在
		List<Long> authoIds = addRoleForm.getAuthoIds();
		if (!isAuthoesAllExist(authoIds)) {
			throw new ServiceException(
					SpringUtils
							.getI18nMessage("webapp.service.RoleManagerImpl.addRole.AuthesNotExist"));
		}
		Role role = createNewRole(addRoleForm);
		Long addId = roleMapper.insert(role);
		// 删除权限信息以重新授权
		authorityMapper.deleteRoleAuthorityByRoleId(addId);
		// 授权权限
		if (authoIds != null && !authoIds.isEmpty()) {
			RoleAuthority roleAuthority;
			for (Long authoId : authoIds) {
				roleAuthority = new RoleAuthority();
				roleAuthority.setAuthorityId(authoId);
				roleAuthority.setRoleId(addId);
				authorityMapper.saveRoleAuthority(roleAuthority);
			}
		}
		role = getRoleWithAuthoes(addId);
		return createRoleRow(role);
	}

	/**
	 * 检查角色名是否已存在.
	 * 
	 * @param name
	 * @param oldId
	 * @return
	 */
	protected boolean isRoleNameExist(String name, Long oldId) {
		Role role = roleMapper.getByName(name);
		if (role != null) {
			if (oldId != null) {
				return !oldId.equals(role.getId());
			}
			return true;
		}
		return false;
	}

	/**
	 * 检查权限是否都存在.
	 * 
	 * @param authoIds
	 * @return
	 */
	protected boolean isAuthoesAllExist(List<Long> authoIds) {
		if (authoIds != null && !authoIds.isEmpty()) {
			for (Long authoId : authoIds) {
				if (authorityMapper.get(authoId) == null) {
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * 创建新角色.
	 * 
	 * @param addRoleForm
	 * @return
	 */
	protected Role createNewRole(AddRoleForm addRoleForm) {
		Role newRole = new Role();

		newRole.setName(addRoleForm.getName());
		newRole.setDisplayName(addRoleForm.getDisplayName());

		return newRole;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.general.op.manager.RoleManager#updateRole(com.general.op.model
	 * .vo.UpdateRoleForm)
	 */
	@Override
	public RoleRow updateRole(UpdateRoleForm updateRoleForm)
			throws ServiceException {
		if (updateRoleForm == null) {
			throw new ServiceException(
					SpringUtils
							.getI18nMessage("webapp.service.RoleManagerImpl.updateRole.FormNotNull"));
		}
		if (updateRoleForm.getId() == null) {
			throw new ServiceException(
					SpringUtils
							.getI18nMessage("webapp.service.RoleManagerImpl.updateRole.IdNotNull"));
		}
		Role role = roleMapper.get(updateRoleForm.getId());
		// 检查角色是否存在
		if (role == null) {
			throw new ServiceException(
					SpringUtils
							.getI18nMessage("webapp.service.RoleManagerImpl.updateRole.NotExist"));
		}
		// 检查角色名是否存在
		if (isRoleNameExist(updateRoleForm.getName(), updateRoleForm.getId())) {
			throw new ServiceException(
					SpringUtils
							.getI18nMessage("webapp.service.RoleManagerImpl.updateRole.IsExist"));
		}
		// 检查权限是否存在
		List<Long> authoIds = updateRoleForm.getAuthoIds();
		if (!isAuthoesAllExist(authoIds)) {
			throw new ServiceException(
					SpringUtils
							.getI18nMessage("webapp.service.RoleManagerImpl.updateRole.AuthesNotExist"));
		}
		role = createUpdateRole(updateRoleForm);
		Integer ret = roleMapper.update(role);
		if(ret != null && ret == 1){
			// 删除权限信息以重新授权
			authorityMapper.deleteRoleAuthorityByRoleId(role.getId());
			// 授权权限
			if (authoIds != null && !authoIds.isEmpty()) {
				RoleAuthority roleAuthority;
				for (Long authoId : authoIds) {
					roleAuthority = new RoleAuthority();
					roleAuthority.setAuthorityId(authoId);
					roleAuthority.setRoleId(role.getId());
					authorityMapper.saveRoleAuthority(roleAuthority);
				}
			}
		}
		role = getRoleWithAuthoes(role.getId());
		return createRoleRow(role);
	}

	/**
	 * 修改角色.
	 * 
	 * @param updateRoleForm
	 * @return
	 */
	protected Role createUpdateRole(UpdateRoleForm updateRoleForm) {
		Role updateRole = new Role();

		updateRole.setId(updateRoleForm.getId());
		updateRole.setName(updateRoleForm.getName());
		updateRole.setDisplayName(updateRoleForm.getDisplayName());

		return updateRole;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.general.op.manager.RoleManager#getAllRoleAuthoes()
	 */
	@Override
	public List<Role> getAllRoleAuthoes() throws ServiceException {

		List<Role> roleList = roleMapper.getAll();
		List<Role> resultRoleList = new ArrayList<Role>(roleList);
		if (roleList != null) {
			List<Authority> authoList = null;
			for (Role role : roleList) {
				authoList = authorityMapper.getByRoleId(role.getId());
				if (authoList != null) {
					role.setAuths(new LinkedHashSet<Authority>(authoList));
					// 检查当前用户是否为超级管理员，如果不是，则去掉具有超级管理员中心各种权限的角色
					for (Authority autho : authoList) {
						if (autho.getName().startsWith(
								SystemConstant.SUPER_ADMIN_AUTHO)) {
							if (!ShiroUtils
									.isPermitted(SystemConstant.SUPER_ADMIN_AUTHO)) {
								resultRoleList.remove(role);
							}
						}
					}
				}
			}
			return resultRoleList;
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.general.op.manager.RoleManager#getRoleWithAuthoes(java.lang.Long)
	 */
	@Override
	public Role getRoleWithAuthoes(Long roleId) throws ServiceException {
		Role role = roleMapper.get(roleId);
		if (role != null) {
			List<Authority> authoList = authorityMapper.getByRoleId(roleId);
			if (authoList != null) {
				role.setAuths(new LinkedHashSet<Authority>(authoList));
			}
		}
		return role;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.general.op.manager.RoleManager#getAllRoles()
	 */
	@Override
	public List<Role> getAllRoles() throws ServiceException {

		List<Role> roleList = roleMapper.getAll();
		List<Role> resultRoleList = new ArrayList<Role>(roleList);
		if (roleList != null) {
			List<Authority> authoList = null;
			for (Role role : roleList) {
				authoList = authorityMapper.getByRoleId(role.getId());
				if (authoList != null) {
					role.setAuths(new LinkedHashSet<Authority>(authoList));
					// 检查当前用户是否为超级管理员，如果不是，则去掉具有超级管理员中心各種权限的角色
					for (Authority autho : authoList) {
						if (autho.getName().startsWith(
								SystemConstant.SUPER_ADMIN_AUTHO)) {
							if (!ShiroUtils
									.isPermitted(SystemConstant.SUPER_ADMIN_AUTHO)) {
								resultRoleList.remove(role);
							}
						}
					}
				}
			}
		}
		return (resultRoleList == null || resultRoleList.isEmpty()) ? null
				: resultRoleList;
	}
}
